/**
 * 性能监控工具
 */

export class PerformanceMonitor {
  private static timers: Map<string, number> = new Map();

  /**
   * 开始计时
   */
  static startTimer(name: string): void {
    this.timers.set(name, performance.now());
    console.log(`⏱️ [${name}] 开始计时`);
  }

  /**
   * 结束计时并输出结果
   */
  static endTimer(name: string): number {
    const startTime = this.timers.get(name);
    if (!startTime) {
      console.warn(`⚠️ 未找到计时器: ${name}`);
      return 0;
    }

    const duration = performance.now() - startTime;
    console.log(`✅ [${name}] 耗时: ${duration.toFixed(2)}ms`);
    this.timers.delete(name);
    return duration;
  }

  /**
   * 监控API调用性能
   */
  static async monitorApiCall<T>(
    name: string,
    apiCall: () => Promise<T>
  ): Promise<T> {
    this.startTimer(name);
    try {
      const result = await apiCall();
      this.endTimer(name);
      return result;
    } catch (error) {
      this.endTimer(name);
      throw error;
    }
  }

  /**
   * 监控视频加载性能
   */
  static monitorVideoLoad(videoElement: HTMLVideoElement): void {
    const startTime = performance.now();
    
    const onLoadStart = () => {
      console.log('📹 视频开始加载');
    };

    const onCanPlay = () => {
      const loadTime = performance.now() - startTime;
      console.log(`✅ 视频加载完成，耗时: ${loadTime.toFixed(2)}ms`);
      cleanup();
    };

    const onError = () => {
      const loadTime = performance.now() - startTime;
      console.log(`❌ 视频加载失败，耗时: ${loadTime.toFixed(2)}ms`);
      cleanup();
    };

    const cleanup = () => {
      videoElement.removeEventListener('loadstart', onLoadStart);
      videoElement.removeEventListener('canplay', onCanPlay);
      videoElement.removeEventListener('error', onError);
    };

    videoElement.addEventListener('loadstart', onLoadStart);
    videoElement.addEventListener('canplay', onCanPlay);
    videoElement.addEventListener('error', onError);
  }

  /**
   * 获取页面性能指标
   */
  static getPagePerformance(): any {
    if (!window.performance || !window.performance.timing) {
      return null;
    }

    const timing = window.performance.timing;
    const navigation = window.performance.navigation;

    return {
      // 页面加载时间
      pageLoadTime: timing.loadEventEnd - timing.navigationStart,
      // DNS查询时间
      dnsTime: timing.domainLookupEnd - timing.domainLookupStart,
      // TCP连接时间
      tcpTime: timing.connectEnd - timing.connectStart,
      // 请求时间
      requestTime: timing.responseEnd - timing.requestStart,
      // 解析DOM树时间
      domParseTime: timing.domComplete - timing.domLoading,
      // 白屏时间
      whiteScreenTime: timing.responseStart - timing.navigationStart,
      // 首屏时间
      firstScreenTime: timing.loadEventEnd - timing.navigationStart,
      // 页面类型
      navigationType: navigation.type,
      // 重定向次数
      redirectCount: navigation.redirectCount
    };
  }

  /**
   * 输出性能报告
   */
  static logPerformanceReport(): void {
    const perf = this.getPagePerformance();
    if (perf) {
      console.group('📊 页面性能报告');
      console.log(`页面加载时间: ${perf.pageLoadTime}ms`);
      console.log(`DNS查询时间: ${perf.dnsTime}ms`);
      console.log(`TCP连接时间: ${perf.tcpTime}ms`);
      console.log(`请求时间: ${perf.requestTime}ms`);
      console.log(`DOM解析时间: ${perf.domParseTime}ms`);
      console.log(`白屏时间: ${perf.whiteScreenTime}ms`);
      console.log(`首屏时间: ${perf.firstScreenTime}ms`);
      console.groupEnd();
    }
  }
}

/**
 * 视频性能优化工具
 */
export class VideoPerformanceOptimizer {
  /**
   * 预加载视频元数据
   */
  static preloadVideoMetadata(url: string): Promise<HTMLVideoElement> {
    return new Promise((resolve, reject) => {
      const video = document.createElement('video');
      video.preload = 'metadata';
      video.crossOrigin = 'anonymous';
      
      video.addEventListener('loadedmetadata', () => {
        console.log(`✅ 视频元数据预加载完成: ${url}`);
        resolve(video);
      });

      video.addEventListener('error', () => {
        console.error(`❌ 视频元数据预加载失败: ${url}`);
        reject(new Error('Video metadata preload failed'));
      });

      video.src = url;
    });
  }

  /**
   * 批量预加载视频元数据
   */
  static async batchPreloadMetadata(urls: string[]): Promise<HTMLVideoElement[]> {
    console.log(`🚀 开始批量预加载 ${urls.length} 个视频的元数据`);
    
    const promises = urls.map(url => 
      this.preloadVideoMetadata(url).catch(error => {
        console.warn(`预加载失败: ${url}`, error);
        return null;
      })
    );

    const results = await Promise.all(promises);
    const successful = results.filter(video => video !== null);
    
    console.log(`✅ 批量预加载完成，成功: ${successful.length}/${urls.length}`);
    return successful as HTMLVideoElement[];
  }

  /**
   * 优化视频元素设置
   */
  static optimizeVideoElement(video: HTMLVideoElement): void {
    // 设置预加载策略
    video.preload = 'metadata';
    
    // 设置播放属性
    video.playsInline = true;
    video.setAttribute('webkit-playsinline', 'true');
    video.setAttribute('x5-video-player-type', 'h5');
    video.setAttribute('x5-video-player-fullscreen', 'true');
    
    // 设置跨域
    video.crossOrigin = 'anonymous';
    
    console.log('✅ 视频元素优化完成');
  }
}
